package blog.service.impl;

import blog.common.Result;
import blog.entity.Login;
import blog.entity.User;
import blog.mapper.UserMapper;
import blog.service.LoginService;
import blog.service.UserService;
import blog.utils.IpUtil;
import blog.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private LoginService loginService;
    @Autowired
    private IpUtil ipUtil;

    @Override
    public Result login(String username, String password, String ip) {
        //校验参数
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return Result.error("用户名或密码不能为空");
        }
        //根据ip查询地区
        String addr = ipUtil.getAddr(ip);
        //根据用户名查询用户
        User user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));


        if (user == null) {
            //设置随机盐
            String salt = String.valueOf(System.currentTimeMillis());
            //加密密码
            String md5Password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            //创建新用户
            User user1 = new User(username, md5Password, salt);
            this.save(user1);
            //查询新用户
            user1 = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
            //登录成功，记录登录日志



            loginService.save(new Login(user1.getId(),user1.getUsername(), ip,addr));
            //返回jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", JwtUtil.getToken(user1.getId().longValue()));
            user1.setPassword(null);
            user1.setSalt(null);
            map.put("user", user1);

            return Result.success(map, "登录成功");

        } else {

            //加密密码
            String md5Password = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());

            //校验密码
            if (!md5Password.equals(user.getPassword())) {
                return Result.error("密码错误");
            }

            //登录成功，记录登录日志
            loginService.save(new Login(user.getId(),user.getUsername(), ip,addr));
            //返回jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", JwtUtil.getToken(user.getId().longValue()));
            user.setPassword(null);
            user.setSalt(null);
            map.put("user", user);
            return Result.success(map, "登录成功");

        }
    }

    @Override
    public Result findUserVisitCount() {
        int count = loginService.count();
        return Result.success(count);
    }

    @Override
    public Result findUserVisitList() {
        //只查询根据创建时间倒序排列的前6条数据
        Page<Login> page = new Page<>(1, 6);
        loginService.page(page, new LambdaQueryWrapper<Login>().orderByDesc(Login::getCreateTime));
        List<Login> loginList = page.getRecords();

        return Result.success(loginList);
    }

    @Override
    public Result updateUser(User user) {
        //校验参数
        if (user == null || user.getId() == null) {
            return Result.error("参数错误");
        }

        //根据id查询用户
        User user1 = this.getById(user.getId());
        if (user1 == null) {
            return Result.error("用户不存在");
        }
        user.setCreateTime(user1.getCreateTime());
        user.setSalt(user1.getSalt());
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(user1.getPassword());
        } else {
            //加密密码
            String md5Password = DigestUtils.md5DigestAsHex((user.getPassword() + user1.getSalt()).getBytes());
            user.setPassword(md5Password);
        }

        this.updateById(user);





        return Result.success(user, "更新成功");
    }


}